<template>
  <div class="login-container" v-loading="isLoading">
    <div class="login-form">
      <el-form :model="loginForm" :rules="rules" ref="loginForm">
        <el-form-item label="" prop="email">
          <el-input v-model="loginForm.email" maxlength="50" placeholder="请输入你的邮箱"></el-input>
        </el-form-item>

        <el-form-item label="" prop="code">
          <el-input placeholder="请输入你的邮箱收到的验证码"
                    maxlength="6"
                    style="width: 274px"
                    v-model="loginForm.code">
          </el-input>

          <el-popover placement="bottom" width="240" trigger="click">
            <el-form :model="loginForm" prop="captcha">
              <el-form-item label="">
                <el-input v-model.trim="loginForm.captcha" maxlength="6" placeholder="请输入下方数字计算结果"></el-input>
              </el-form-item>

              <el-form-item label="">
                <el-image :src="loginForm.captchaImgData" fit="fill" class="captcha-img" @click="doGetCaptcha">
                  <div slot="error" style="text-align: center; font-size: 12px;" @click="doGetCaptcha">
                    点击这里显示图片验证码
                  </div>
                  <div slot="placeholder" style="text-align: center; font-size: 12px;">
                    加载验证码中...
                  </div>
                </el-image>
              </el-form-item>

              <div style="position: relative; top: -10px;">
                <el-button style="width: 100%; height: 40px"
                           size="small"
                           :disabled="isDisableCaptchaBtn"
                           @click="doSendCodeToMyEmail" type="info" plain>
                  <span v-if="loginForm.getCaptchaMsg.length > 0">{{loginForm.getCaptchaMsg}}</span>
                  <span v-else-if="loginForm.getEmailCodeMsg.length > 0">{{loginForm.getEmailCodeMsg}}</span>
                  <span v-else>发送验证码到我邮箱</span>
                </el-button>
              </div>
            </el-form>

            <el-button slot="reference">
              <span v-if="!isGettingCode">获取验证码</span>
              <span v-else>验证码发送中</span>
            </el-button>

          </el-popover>
        </el-form-item>

        <div style="margin-top: 48px">
          <el-button :disabled="isDisableLoginBtn" type="success" style="width: 100%" @click="doLogin">登 录</el-button>
        </div>
      </el-form>
    </div>

  </div>
</template>

<script>
import {REG_EMAIL} from '../../utils/regExpUtil'
import {currentAppClientId} from '../../utils/AppConstant'
const CryptoJS = require('crypto-js')

export default {
  name: 'Login',
  data () {
    return {
      isLoading: false,
      loginForm: {
        email: '',
        captcha: '',
        code: '',
        captchaImgData: '',
        getCaptchaMsg: '',
        getEmailCodeMsg: '',
        loginMsg: ''
      },
      rules: {
        email: [{required: true, message: '请输入你的邮箱', trigger: 'blur'},
          {min: 1, max: 50, message: '长度在 1 到 50 个字符的邮件地址', trigger: 'blur'},
          {pattern: REG_EMAIL, message: '请输入正确的邮件地址'}],
        captcha: [{required: true, message: '请输入获取邮件验证码', trigger: 'blur'},
          {min: 1, max: 4, message: '验证码长度在4个字符', trigger: 'blur'}],
        code: [{required: true, message: '请输入收到的验证码', trigger: 'blur'},
          {min: 1, max: 6, message: '验证码长度在6个字符', trigger: 'blur'}]
      },
      isSubmitting: false,
      isGettingCode: false
    }
  },
  computed: {
    isDisableCaptchaBtn: function () {
      if (this.loginForm.getCaptchaMsg.length > 0) {
        return true
      }
      if (this.loginForm.getEmailCodeMsg.length > 0) {
        return true
      }
      return false
    },
    isDisableLoginBtn: function () {
      const isCaptchaOK = this.isDisableCaptchaBtn
      if (isCaptchaOK === true) {
        return isCaptchaOK
      }
      if (this.loginForm.loginMsg.length > 0) {
        return true
      }
      if (this.loginForm.code < 6) {
        return true
      }
      return false
    }
  },
  created () {
  },
  mounted () {
    this.doGetCaptcha()
  },
  methods: {
    doGetCaptcha () {
      if (this.loginForm.getCaptchaMsg.length > 0) {
        return
      }
      this.loginForm.getCaptchaMsg = '获取图片验证码中...'
      const param = {'uuid': currentAppClientId()}
      this.$post('api/AppUserVc/appLoginCaptcha', param).then(resp => {
        const imgData = 'data:image/svg+xml;base64,' + CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(resp))
        this.loginForm.captchaImgData = imgData
      }).finally(() => {
        this.loginForm.getCaptchaMsg = ''
      })
    },
    doSendCodeToMyEmail () {
      if (this.loginForm.captcha.length <= 0) {
        this.$message.error('请先填写图片验证码')
        return false
      }
      if (REG_EMAIL.test(this.loginForm.email.trim()) === false) {
        this.$message.error('请输入正确的邮箱地址')
        return false
      }

      this.loginForm.getEmailCodeMsg = '发送验证码到邮箱中'
      const param = {email: this.loginForm.email.trim(), answer: this.loginForm.captcha, uuid: currentAppClientId()}
      this.$post('api/AppUserVc/getLoginCode', param).then(resp => {
        this.$message.success('验证码已发送到你邮箱,请注意查收')
      }).catch(() => {
        // this.doGetCaptcha()
      }).finally(() => {
        this.loginForm.getEmailCodeMsg = ''
      })
    },
    doLogin () {
      this.$refs.loginForm.validate((validated) => {
        if (validated === false) {
          this.$message.warning('请填写完整信息')
          return false
        }

        const param = {
          uuid: currentAppClientId(),
          email: this.loginForm.email.trim(),
          code: this.loginForm.code.trim()
        }
        this.loginForm.loginMsg = '登录中...'
        this.$post('api/AppUserVc/login', param).then(resp => {
          const userInfo = {
            id: resp.userInfo.id,
            email: resp.userInfo.email,
            nickname: resp.userInfo.nickname,
            isDisable: resp.userInfo.isDisable,
            token: resp.accessToken
          }
          this.$store.dispatch('setUserInfo', userInfo)
          this.$router.push({name: 'Home'})
          this.$message.success('登录成功')
        }).finally(() => {
          this.loginForm.loginMsg = ''
        })
      })
    }
  }
}
</script>

<style scoped>
  * {
    font-size: 16px;
  }

  *:focus {
    outline: none;
  }

  .login-container {
    border: 1px solid green;
    height: 100%;
    position: relative;
  }

  .login-form {
    position: absolute;
    width: 400px;
    left: 50%;
    /*border: 1px solid lightgray;*/
    top: 150px;
    transform: translateX(-50%);
    /*background: white;*/
    /*min-height: 100px;*/
  }

  .message {
    text-align: center;
    font-size: 10px;
    color: darkgrey;
    margin-top: 8px
  }

  .captcha-img {
    width: 100%;
    height: 40px;
    background: lightgrey;
    border-radius: 4px;
    border: 1px solid #CCCCCC;
  }

</style>
